<template>
  <div class="container-box">
    <el-row>
      <el-col ><el-button @click="$router.go(-1)" icon="el-icon-arrow-left">返回</el-button></el-col>
      <el-col  class="page-title-box">
        <span class="page-title" v-if="type">创建多选投票</span>
        <span class="page-title" v-else>创建单选投票</span>
      </el-col>
    </el-row>
    <el-row class="top-input-box">
      <!-- input分部 -->
      <el-row class="item-input-box">
        <el-col>
          <el-input class="title" placeholder="投票标题" v-model="title" clearable>
          </el-input>
        </el-col>
      </el-row>
      <el-row class="item-input-box">
        <el-col>
          <el-input
            placeholder="补充描述(选填)"
            v-model="titleDetail"
            clearable
          >
          </el-input>
        </el-col>
      </el-row>

      <!-- 选项标签 -->
      <el-row
        class="icon-input-box"
        v-for="(item, index) in iconList"
        :key="index"
      >
        <el-col :span="2" class="icon-left-dle" @click="delIconItem(item.id)">
          <span class="el-icon-circle-close"></span>
        </el-col>
        <el-col :span="20" :offset="1" class="icon-right-input">
            <el-input placeholder="选项" v-model="item.content"> </el-input>
        </el-col>
      </el-row>

      <!-- 添加选项 -->
      <el-row  @click="addIconItem" class="icon-input-box">
        <el-col :span="2"  class="icon-left-add">
          <span class="el-icon-circle-plus-outline"></span>
        </el-col>
        <el-col :span="20" :offset="1" class="icon-right-input" style="line-height:40px;border-bottom:1px solid #eee;" >添加选项</el-col>
      </el-row>
    </el-row>

    <!--选择投票限制部分 -->
    <el-row class="footer-astrict">
        <el-row type="flex" justify="" class="date item">
            <el-col :span="12">截止日期</el-col>
            <el-col :span="12">
                <el-input type="date" v-model="date" placeholder="请输入日期"></el-input>
            </el-col>

        </el-row>
        <el-row class="item" > 
            <el-col :span="12">匿名投票</el-col>
            <el-col :span="12" class="item-right"><el-switch v-model="voteSwitch"   active-color="#409EFF" inactive-color="#DCDFE6"></el-switch></el-col>
        </el-row>


    </el-row>

    <!-- 保存按钮 -->
    <el-row class="save">
        <el-col><el-button @click="saveInfo"  type="primary">完成</el-button></el-col>
    </el-row>

  </div>
</template>

<script type="text/ecmascript-6">
import { defineComponent, ref, watch,onUnmounted } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from 'element-plus'
import { useRouter } from "vue-router";
import { apiCreateVote,apiEditVote,apiUpdateVote } from '../api/index'

export default defineComponent({
  name: "VoteEdit",
  setup() {
    const router = useRouter()
    const user_id = JSON.parse(window.sessionStorage.getItem('info')).id

    //投票的唯一项
    const vote_id = JSON.parse(window.sessionStorage.getItem('voteId'))

    const route = useRoute();
    //单选(0)还是多选(1)
    let type = route.params.type *1;
    console.log(typeof type,type)
    //添加选项的数组
    const iconList = ref([]);
    //标题
    let title = ref("");
    //详细
    let titleDetail = ref("");
    //匿名投票
    let voteSwitch = ref(false)
    //结束日期
    let date = ref('')

    

    //保存重新编辑中被删除的投票项
    let delIconlist = ref([])


    //为iconList数组添加元素
    function addIconItem(){
      let leng = iconList.value.length
      let id = 0
      if ( leng != 0 ){
        id =  iconList.value[leng - 1].id+1 
      }
        iconList.value.push({
            id,
            content:''
        })

    }

    //删除iconList数组指定元素
    function delIconItem(id){
      //返回当前删除的数组
      const currentObj = iconList.value.filter(item => item.id == id )
      //如果当前数组中有投票选项的Id，则不是刚添加的，将其id保存起来，修改api需要这个字段
      currentObj[0].vote_id ? delIconlist.value.push(id) : null
      //过滤掉当前删除的元素
      iconList.value = iconList.value.filter(item=> item.id != id)
      console.log(delIconlist.value)
    }

    //投票项id存在,获取数据
    if ( vote_id ){
      getVoteInfo(vote_id)
    }
    async function getVoteInfo(vote_id){
      const result = await apiEditVote(vote_id)
      if ( result.err_code == 200 ){
        let { anonymous,describe,end_time,option } = result.data
        voteSwitch.value = anonymous*1 ?  false : true
        titleDetail.value = describe
        title.value = result.data.title
        iconList.value = option
        date.value = end_time.split(" ")[0]

        
        return
      }
      ElMessage.error(result.message);
    }


    //提交信息
    async function saveInfo(){
      //校验数据,为true才执行之后代码
      if ( !verify()){
        return
      }
      let options = []
      //重新编辑的将数组保留: [ {option_id:xx,content:xx} ]格式
      if ( vote_id ){
        options = iconList.value.map( item =>{
          //新添加的选项
          if ( !item.vote_id){
            return {option_id:null,content:item.content}
          } 
          //本来就存在的
          return {option_id:item.id,content:item.content}
        })
      }else{
        //创建的过滤数组中的文字出来
          options = iconList.value.map( item => item.content)
      }


      //判断是修改还是创建
      let result 
      let anonymous = voteSwitch.value ? 0 : 1
      if ( vote_id ){
        result = await apiUpdateVote(vote_id,title.value,titleDetail.value,new Date().toLocaleDateString(),date.value,type,options,delIconlist.value,anonymous)
        window.sessionStorage.removeItem('voteId')
      }else{
        result = await apiCreateVote(user_id,title.value,titleDetail.value,options,type,anonymous,date.value)
      } 

      //成功
      if ( result.err_code == 200 ){
        ElMessage.success({
          message: result.message,
          type: 'success'
        });
        title.value = null
        titleDetail.value = null
        voteSwitch.value = false
        date.value = null
        iconList.value = []
        delIconlist.value = []
        result.data ? router.push(`/VoteDetail/${result.data.vote_id}`) : null
        return
      }
      //失败
      ElMessage.error(result.message);

    }
    //提交时校验
    function verify(){
      let currentDate = new Date().toLocaleDateString()
      if ( !title.value.trim() ){
        ElMessage.error('标题不能为空');
        return 
      }
      if ( !date.value ){
        ElMessage.error('截止日期不能为空');
        return 
      }
      if ( new Date(currentDate) > new Date(date.value) ){
        ElMessage.error('截止日期不能早于今天');
        return 
      }
      if ( iconList.value.length == 0){
        ElMessage.error('请添加选项');
        return 
      }

      for (let index = 0; index < iconList.value.length; index++) {
        if ( ! iconList.value[index].content){
          ElMessage.error('选项内容不能空');
          return
        }      
      }
      
      return true
    }

    onUnmounted(()=>{
      window.sessionStorage.removeItem('voteId')
    })


    return {
      type,
      title,
      titleDetail,
      iconList,
      date,
      voteSwitch,
      addIconItem,
      delIconItem,
      saveInfo
    };
  },
});
</script>

<style scoped lang="less" >
@back:#789eff;
.container-box {
  min-height: 98vh;
  // background: white;
  background-image: -webkit-linear-gradient(331deg, #7eeecf 0%, #8ce8ec 50%, #95eef3 10%);
  padding: 0px 4vw;

  padding-top: 2vh;
  .page-title-box{
    text-align: center;
    .page-title{
      line-height: 30px;
      font-size: 16px;
      color: @back;
    }
  }

  .item-input-box {
    margin-top: 10px;
    width: 100%;
    .el-input {
      width: 100%;
    }
  }
  
  .icon-input-box{
    margin-top: 10px;
    width: 100%;
    background: white;
    .icon-left-dle {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-left: 10px;
        justify-content: center;
        color: red;
        font-size: 22px;
    }
    .icon-left-add {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
        color: @back;
        height: 40px;
        font-size: 22px;
    }

    .icon-right-input{
        width: 100%;
        .el-input {
        width: 100%;
        }
    }
  }

  .footer-astrict{
      margin-top: 20px;
      .item{
        padding: 0px 2vw;
        margin-bottom: 10px;
        border-radius: 5px;
        width: 100%;
        line-height: 40px;
        background: white;
        border-bottom: 1px solid #eee;
          .item-right{
              text-align: right;
          }
      }
  }

  .save{
      .el-button{
          margin: 20px 0px;
          width: 100%;
      }
  }
}


@media screen and (max-width:770px) {
  .container-box /deep/ .el-input__inner{
    border: none !important;
    border-bottom: 1px solid #eee !important;
  }
  .container-box /deep/  .el-button--default{
    padding: 6px 10px  !important;
  }
}

@media screen and (min-width:770px) {
  .container-box{
    padding: 20px 6vw;
  }
  .container-box /deep/ .el-input__inner{
    border: none !important;
    border-bottom: 1px solid #eee !important;
  }
}


</style>
